package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    /**
     * 锁前缀标识
     */
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 业务名称类型
     */
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private static final String LOCK_PREFIX = "LOCK:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";

    private static final DefaultRedisScript<Long> SCRIPT;

    static {
        SCRIPT = new DefaultRedisScript<>();
        SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        SCRIPT.setResultType(Long.class);
    }


    @Override
    public boolean tryLock(long timeout) {
        // 获取线程的标识
        String id = ID_PREFIX+Thread.currentThread().getId();
        // value是线程ID
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, id , timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag); // 包装类转换基本类自动拆箱问题
    }

    @Override
    public void unlock() {
        // 调用lua脚本
        stringRedisTemplate.execute(SCRIPT, Collections.singletonList(LOCK_PREFIX + name), ID_PREFIX+Thread.currentThread().getId());

    }
    @Deprecated
//    @Override
    public void unlock1() {
        // 获取线程的标识
        String id = ID_PREFIX+Thread.currentThread().getId();
        // 获取锁中的线程标识
        String key = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
        //判断标识是否一致
        assert key != null;
        if (key.equals(id)){
            // 释放锁
            stringRedisTemplate.delete(LOCK_PREFIX + name);
        }

    }
}
